package db

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/jinzhu/gorm"
	"sola/common"
	"time"
)

type Category struct {
	common.BaseModel
	CategoryId         string `json:"category_id" uri:"category_id" gorm:"size:36;NOT NULL"`
	CategoryName       string `json:"category_name" gorm:"size:64;NOT NULL"`
	ClassifyId         string `json:"classify_id" gorm:"size:36;NOT NULL"`
	ClassifyName       string `json:"classify_name" gorm:"size:64;NOT NULL"`
	AuthorId           string `json:"author_id" gorm:"size:36"`
	AuthorName         string `json:"author_name" gorm:"size:64"`
	AuthorNickName     string `json:"author_nick_name" gorm:"size:64"`
	UpdateUserId       string `json:"update_user_id" gorm:"size:36"`
	UpdateUserName     string `json:"update_user_name" gorm:"size:64"`
	UpdateUserNickName string `json:"update_user_nick_name" gorm:"size:64"`
	Status             string `json:"status"`
}

func (category *Category) BeforeCreate(scope *gorm.Scope) error {
	return scope.SetColumn("category_id", uuid.New().String())
}

func (category *Category) BeforeSave(scope *gorm.Scope) error {
	return scope.SetColumn("updated_at", time.Now())
}

func CountCategory(searchModel *common.BaseSearchModel) (count int) {
	searchDB := db.Table("categories")
	if searchModel.UserId != "" {
		searchDB = searchDB.Where("author_id = ?", searchModel.UserId)
	}
	if searchModel.ClassifyId != "" {
		searchDB = searchDB.Where("classify_id = ?", searchModel.ClassifyId)
	}
	searchDB.Where("category_name like ? and status like ? and deleted_at is  NULL", "%"+searchModel.Name+"%", "%"+searchModel.Status+"%").Count(&count)
	return
}

func GetCategoryList(searchModel *common.BaseSearchModel) (categories []*Category) {
	searchDB := db.Table("categories")
	if searchModel.UserId != "" {
		searchDB = searchDB.Where("author_id = ?", searchModel.UserId)
	}
	if searchModel.ClassifyId != "" {
		searchDB = searchDB.Where("classify_id = ?", searchModel.ClassifyId)
	}
	searchDB = searchDB.Where("category_name like ? and status like ?",
		"%"+searchModel.Name+"%", "%"+searchModel.Status+"%")
	if searchModel.Limit > 0 {
		searchDB = searchDB.Offset((searchModel.Page - 1) * searchModel.Limit).Limit(searchModel.Limit)
	}
	if searchModel.Sort != "" {
		searchDB = searchDB.Order(searchModel.Sort)
	}
	searchDB.Find(&categories)
	return categories
}

func FindByCategoryId(category_id string) (category *Category, err error) {
	var category_db Category
	category_db.CategoryId = category_id
	db.Where("category_id = ?", category_id).First(&category_db)
	if category_db.Id <= 0 {
		err = fmt.Errorf("classify:%s is not found", category_id)
		return
	}
	category = &category_db
	return
}
